package http

import (
	permissionApp "furniture-server-gin/api/pkg/application/permission"
	"net/http"

	"github.com/gin-gonic/gin"
)

type permissionController struct {
	permissionService *permissionApp.Service
}

// NewPermissionController 创建权限控制器
func NewPermissionController(permissionService *permissionApp.Service) *permissionController {
	return &permissionController{
		permissionService: permissionService,
	}
}

// CreatePermission 创建权限
func (c *permissionController) CreatePermission(ctx *gin.Context) {
	var req struct {
		Name        string `json:"name" binding:"required"`
		Description string `json:"description"`
		Resource    string `json:"resource" binding:"required"`
		Action      string `json:"action" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := c.permissionService.CreatePermission(req.Name, req.Description, req.Resource, req.Action); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusCreated, gin.H{"message": "Permission created successfully"})
}

// GetPermissions 获取所有权限
func (c *permissionController) GetPermissions(ctx *gin.Context) {
	permissions, err := c.permissionService.GetAllPermissions()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"permissions": permissions})
}

// GetPermission 获取单个权限
func (c *permissionController) GetPermission(ctx *gin.Context) {
	id := ctx.Param("id")

	permission, err := c.permissionService.GetPermissionByID(id)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "Permission not found"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"permission": permission})
}
